package com.zust513.controller;

import com.zust513.dto.CourierDTO;
import com.zust513.dto.ExpenseDTO;
import com.zust513.dto.IncomeDTO;
import com.zust513.service.CourierService;
import com.zust513.service.FinanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.format.TextStyle;
import java.util.*;

/**
 * 财务管理控制器
 */
@Controller
@RequestMapping("/admin")
public class FinanceController {

    @Autowired
    private FinanceService financeService;

    @Autowired
    private CourierService courierService;

    /**
     * 收入明细页面 (F0040301)
     */
    @GetMapping("/income")
    public String incomePage(Model model) {
        List<IncomeDTO> incomeRecords = financeService.getAllIncomeRecords();
        BigDecimal totalIncome = financeService.getTotalIncome();

        // 构造图表数据
        Map<String, Object> chartData = generateChartData(incomeRecords);

        // 计算其他统计数据
        BigDecimal monthlyIncome = calculateMonthlyIncome(incomeRecords);
        BigDecimal weeklyIncome = calculateWeeklyIncome(incomeRecords);
        BigDecimal dailyIncome = calculateDailyIncome(incomeRecords);

        // 计算增长率
        int monthGrowth = 15; // 示例数据，实际项目中应从数据库计算
        int weekGrowth = 8;   // 示例数据，实际项目中应从数据库计算

        model.addAttribute("records", incomeRecords);
        model.addAttribute("totalIncome", formatAmount(totalIncome));
        model.addAttribute("monthlyIncome", formatAmount(monthlyIncome));
        model.addAttribute("weeklyIncome", formatAmount(weeklyIncome));
        model.addAttribute("dailyIncome", formatAmount(dailyIncome));
        model.addAttribute("monthGrowth", monthGrowth);
        model.addAttribute("weekGrowth", weekGrowth);
        model.addAttribute("chartData", chartData);

        model.addAttribute("view", "admin/income");
        return "admin/index";
    }

    /**
     * 支出明细页面 (F0040302)
     */
    @GetMapping("/expenses")
    public String expensesPage(@RequestParam(required = false) Integer courierId, Model model) {
        List<ExpenseDTO> expenseRecords;

        if (courierId != null) {
            expenseRecords = financeService.getCourierExpensesByCourierId(courierId);
        } else {
            expenseRecords = financeService.getAllCourierExpenses();
        }

        BigDecimal totalExpense = financeService.getTotalExpense();

        // 构造图表数据
        Map<String, Object> chartData = generateChartData(expenseRecords);

        // 计算其他统计数据
        BigDecimal monthlyExpense = calculateMonthlyExpense(expenseRecords);
        BigDecimal weeklyExpense = calculateWeeklyExpense(expenseRecords);
        BigDecimal dailyExpense = calculateDailyExpense(expenseRecords);

        // 计算增长率
        int monthGrowth = 12; // 示例数据，实际项目中应从数据库计算
        int weekGrowth = 5;   // 示例数据，实际项目中应从数据库计算

        // 获取所有配送员信息，用于下拉选择框
        List<CourierDTO> couriers = courierService.getAllCouriers();

        model.addAttribute("records", expenseRecords);
        model.addAttribute("totalExpense", formatAmount(totalExpense));
        model.addAttribute("monthlyExpense", formatAmount(monthlyExpense));
        model.addAttribute("weeklyExpense", formatAmount(weeklyExpense));
        model.addAttribute("dailyExpense", formatAmount(dailyExpense));
        model.addAttribute("monthGrowth", monthGrowth);
        model.addAttribute("weekGrowth", weekGrowth);
        model.addAttribute("chartData", chartData);
        model.addAttribute("couriers", couriers);

        model.addAttribute("view", "admin/expenses");
        return "admin/index";
    }

    /**
     * API接口：查看总收入 (F0040301)
     */
    @GetMapping("/api/finance/income")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getIncomeDetails() {
        List<IncomeDTO> incomeRecords = financeService.getAllIncomeRecords();
        BigDecimal totalIncome = financeService.getTotalIncome();

        Map<String, Object> response = new HashMap<>();
        response.put("records", incomeRecords);
        response.put("totalIncome", totalIncome);

        return ResponseEntity.ok(response);
    }

    /**
     * API接口：查看配送人员支出 (F0040302)
     */
    @GetMapping("/api/finance/expenses")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getExpenseDetails() {
        List<ExpenseDTO> expenseRecords = financeService.getAllCourierExpenses();
        BigDecimal totalExpense = financeService.getTotalExpense();

        Map<String, Object> response = new HashMap<>();
        response.put("records", expenseRecords);
        response.put("totalExpense", totalExpense);

        return ResponseEntity.ok(response);
    }

    /**
     * API接口：查看特定配送员的支出明细
     */
    @GetMapping("/api/finance/expenses/courier/{courierId}")
    @ResponseBody
    public ResponseEntity<List<ExpenseDTO>> getCourierExpenses(@PathVariable Integer courierId) {
        List<ExpenseDTO> expenseRecords = financeService.getCourierExpensesByCourierId(courierId);
        return ResponseEntity.ok(expenseRecords);
    }

    /**
     * 格式化金额，保留两位小数
     */
    private String formatAmount(BigDecimal amount) {
        return amount.setScale(2, java.math.RoundingMode.HALF_UP).toString();
    }

    /**
     * 生成图表数据
     */
    private Map<String, Object> generateChartData(List<?> records) {
        Map<String, Object> chartData = new HashMap<>();
        List<String> labels = new ArrayList<>();
        List<BigDecimal> values = new ArrayList<>();

        // 生成过去6个月的标签
        LocalDateTime now = LocalDateTime.now();
        for (int i = 5; i >= 0; i--) {
            LocalDateTime monthDate = now.minusMonths(i);
            String monthName = monthDate.getMonth().getDisplayName(TextStyle.SHORT, Locale.CHINA);
            labels.add(monthName);

            // 示例数据，实际项目中应从数据库计算
            values.add(new BigDecimal(1000 + i * 400));
        }

        chartData.put("labels", labels);
        chartData.put("values", values);

        return chartData;
    }

    /**
     * 计算本月收入
     */
    private BigDecimal calculateMonthlyIncome(List<IncomeDTO> records) {
        // 示例实现，实际项目中应基于记录计算
        return new BigDecimal("3456.00");
    }

    /**
     * 计算本周收入
     */
    private BigDecimal calculateWeeklyIncome(List<IncomeDTO> records) {
        // 示例实现，实际项目中应基于记录计算
        return new BigDecimal("1234.00");
    }

    /**
     * 计算今日收入
     */
    private BigDecimal calculateDailyIncome(List<IncomeDTO> records) {
        // 示例实现，实际项目中应基于记录计算
        return new BigDecimal("345.00");
    }

    /**
     * 计算本月支出
     */
    private BigDecimal calculateMonthlyExpense(List<ExpenseDTO> records) {
        // 示例实现，实际项目中应基于记录计算
        return new BigDecimal("2345.00");
    }

    /**
     * 计算本周支出
     */
    private BigDecimal calculateWeeklyExpense(List<ExpenseDTO> records) {
        // 示例实现，实际项目中应基于记录计算
        return new BigDecimal("876.00");
    }

    /**
     * 计算今日支出
     */
    private BigDecimal calculateDailyExpense(List<ExpenseDTO> records) {
        // 示例实现，实际项目中应基于记录计算
        return new BigDecimal("234.00");
    }
}

